package com.agnes.network.observer;

import android.text.TextUtils;

import com.agnes.network.Const;
import com.agnes.network.callback.RespCallback;
import com.agnes.network.entity.ResultEntity;
import com.agnes.network.util.GsonRespParser;
import com.agnes.network.util.JsonUtils;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import io.reactivex.disposables.CompositeDisposable;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Desc:  D 泛指 实体类或者字符串
 * Creator ling
 * Date:   2017/9/28 0028 15:17
 */

public class DataObserver<D> extends ApiObserver<D> {
    private int mDataType;

    private Class mClazz;

    public DataObserver(RespCallback<D> responseCallback, CompositeDisposable compositeDisposable) {
        super(responseCallback, compositeDisposable);

        Type genType = mResponseCallback.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        mClazz = (Class) params[0];
    }

    @Override
    public void onSuccess(String response) {
        JSONObject rootJO = JsonUtils.parseJO(response);
        if (rootJO != null) {
            String convertResponse = convert(rootJO);
            ResultEntity<D> entity = parseJsonObject(convertResponse);
            if (entity != null) {
                if (Const.SUCCESS_CODE.equals(entity.code)) {
                    mResponseCallback.onSuccess(entity.message, entity.data);
                } else {
                    mResponseCallback.onError(entity.code, entity.message, entity.data);
                }
            } else {
                onFailure("parse to ResultEntity failure!!!");
            }
        } else {
            //如果data未空就直接抛出异常了
            onFailure("result is not json object format!!!");
        }
    }

    /**
     * 如果data为空，则返回 "data":{}.否则会出现解析异常
     *
     * @param rootJO
     * @return
     */
    private String convert(JSONObject rootJO) {
        String rootJson = rootJO.toString();
        String data = rootJO.optString(Const.KEY_DATA);
        if (TextUtils.isEmpty(data)) {
            rootJO.remove(Const.KEY_DATA);
            StringBuilder builder = new StringBuilder(rootJO.toString());
            builder = builder.deleteCharAt(builder.length() - 1);
            builder.append(",")
                    .append(Const.KEY_DATA)
                    .append(":")
                    .append('{')
                    .append('}')
                    .append("}");
            rootJson = builder.toString();
        }

        return rootJson;
    }

    private ResultEntity<D> parseJsonObject(String response) {
        Type gsonType = new GsonRespParser(ResultEntity.class, new Class[]{mClazz});
        ResultEntity<D> entity = null;
        try {
            entity = new Gson().fromJson(response, gsonType);
        } catch (Exception e) {
            Logger.e(e.toString());
        }
        return entity;
    }
}
